

package com.bitland.demo.microservice1.aspect;

import com.bitland.demo.microservice1.annotation.PermissionCheck;
import java.lang.reflect.Method;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class PermissionCheckAspect {
    private static final Logger log = LoggerFactory.getLogger(PermissionCheckAspect.class);

    public PermissionCheckAspect() {
    }

    @Pointcut("@annotation(com.bitland.demo.microservice1.annotation.PermissionCheck)")
    private void permissionCheckCut() {
    }

    @Around("permissionCheckCut()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        Signature signature = proceedingJoinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature)signature;
        Method targetMethod = methodSignature.getMethod();
        if (targetMethod.isAnnotationPresent(PermissionCheck.class)) {
            PermissionCheck permission = (PermissionCheck)targetMethod.getAnnotation(PermissionCheck.class);
            String permissionPoint = permission.permissionPoint();
            //一般从数据库中读取用户权限， 目前 hard code 演示
            String permissionFromDatabase = "insertDataPermission";
            // 权限点匹配， 有权限
            if (StringUtils.isNotEmpty(permissionPoint) && permissionPoint.equals(permissionFromDatabase)) {
                return proceedingJoinPoint.proceed();
            }
        }

        return "无权限访问";
    }
}
